package com.lzy.business.facade;

import com.github.pagehelper.PageInfo;
import com.lzy.base.apis.DeptServiceApi;
import com.lzy.base.apis.SysUserAdminServiceApi;
import com.lzy.base.dtos.DeptDto;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.common.apis.PresentServiceApi;
import com.lzy.common.dtos.PresentDto;
import com.lzy.coupon.apis.CouponServiceApi;
import com.lzy.coupon.dtos.CouponDto;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.DateUtil;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.framework.tools.commons.BigDecimalUtil;
import com.lzy.framework.tools.kv.KvClient;
import com.lzy.member.apis.MemberAccountServiceApi;
import com.lzy.member.apis.MemberCouponServiceApi;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.member.dtos.MemberAccountDto;
import com.lzy.member.dtos.MemberCouponDto;
import com.lzy.member.dtos.MemberUserDto;
import com.lzy.payment.apis.PayMemberAccountApi;
import com.lzy.payment.dtos.memberAccount.LzLargessParamDTO;
import com.lzy.product.apis.*;
import com.lzy.product.common.util.CalendarUtil;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by WIN7 on 2017/12/05.
 */
@Component
public class OrderProductFacade {
    @Autowired
    private OrderProductImageServiceApi orderProductImageServiceApi;
    @Autowired
    private SysUserAdminServiceApi sysUserAdminServiceApi;
    @Autowired
    private OrderProductServiceApi orderProductServiceApi;
    @Autowired
    private DeptServiceApi deptServiceApi;
    @Autowired
    private ProductInfoServiceApi productInfoServiceApi;
    @Autowired
    private ProjectServiceApi projectServiceApi;
    @Autowired
    private OrderProjectRecordServiceApi orderProjectRecordServiceApi;
    @Autowired
    private MemberUserServiceApi memberUserServiceApi;
    @Autowired
    private ProductInfoProjectServiceApi productInfoProjectServiceApi;
    @Autowired
    private OrderYieldRatioServiceApi orderYieldRatioServiceApi;
    @Autowired
    private CouponProfitRecordServiceApi couponProfitRecordServiceApi;
    @Autowired
    private MemberCouponsServiceApi memberCouponsServiceApi;
    @Autowired
    OrderProfitServiceApi orderProfitServiceApi;
    @Autowired
    MemberAccountServiceApi memberAccountServiceApi;
    @Autowired
    PayMemberAccountApi payMemberAccountApi;
    @Autowired
    PresentServiceApi presentServiceApi;
    @Autowired
    CouponServiceApi couponServiceApi;
    @Autowired
    MemberCouponServiceApi memberCouponServiceApi;
    @Autowired
    OrderCouponServiceApi orderCouponServiceApi;
    @Autowired
    KvClient kvClient;

    /**
     * 手动确认线下支付过的待支付订单信息提交
     *
     * @param orderProductImageDto
     * @return
     */
    public Boolean offlineSubmit(OrderProductImageDto orderProductImageDto) {
        Boolean flag = Boolean.TRUE;
        for (String image : orderProductImageDto.getImages()) {
            OrderProductImageDto orderProductImage = new OrderProductImageDto();
            orderProductImage.setOrderId(orderProductImageDto.getOrderId());
            orderProductImage.setImage(image);
            Long id = orderProductImageServiceApi.insert(orderProductImageDto);
            if (id <= 0)
                flag = Boolean.FALSE;
        }
        Ensure.that(flag).isTrue("04000002");
        //业务开始
        //1.修改订单信息
        OrderProductDto orderProductDto = new OrderProductDto();
        orderProductDto.setOrderId(orderProductImageDto.getOrderId());
        orderProductDto.setStatus(BusinessType.OrderType.PAYSUCCESS.getCode());//购买成功状态
        orderProductDto.setPayWay(BusinessType.PayWay.offLine.getCode());//支付方式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        orderProductDto.setPayTime(df.format(new Date()));
        Boolean ok = orderProductServiceApi.update(orderProductDto);
        Ensure.that(ok).isTrue("");
        //2.将产品内容送至客户
        OrderProductDto orderDto = orderProductServiceApi.findById(orderProductImageDto.getOrderId());
        if (orderDto != null) {
            //订单分利
            orderProductServiceApi.calculateProfit(orderDto);
            List<OrderProjectRecordDto> list = orderProjectRecordServiceApi.selectOrderProjectRecordByOrderId(orderDto.getOrderId());
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
            paymentDistribution(list, orderDto);
        }
        return Boolean.TRUE;
    }

    /**
     * 查询产品订单列表
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    public PageInfo orderProductList(Pager pager, OrderProductDto orderProductDto) {
        PageInfo<OrderProductDto> pageInfo = orderProductServiceApi.selectList(pager, orderProductDto);
        //销售员信息
        if (null != pageInfo && null != pageInfo.getList() && pageInfo.getList().size() > 0) {
            for (OrderProductDto o : pageInfo.getList()) {
                SysUserAdminDto sysUserAdminDto = sysUserAdminServiceApi.selectByPrimaryKey(o.getCreateUser());
                if (sysUserAdminDto != null)
                    o.setUserName(sysUserAdminDto.getRealName());
                else
                    o.setUserName("无");
                //根据产品id获取订单卡券类型
                if (o.getProductId() != null) {
                    ProductInfoDto infoDto = productInfoServiceApi.findById(o.getProductId());
                    if (infoDto != null && infoDto.getName() != null) {
                        o.setProductName(infoDto.getName());
                    }
                    //获取卡券类型（如“房车券 + 代金券”）
                    ProductInfoProjectDto pipDto = new ProductInfoProjectDto();
                    pipDto.setProductId(o.getProductId());
                    List<ProductInfoProjectDto> pipList = productInfoProjectServiceApi.query(pipDto);
                    if (pipList != null && pipList.size() > 0) {
                        String couponName = "";
                        for (ProductInfoProjectDto proInfoProDto : pipList) {
                            if (proInfoProDto != null && proInfoProDto.getName() != null) {
                                couponName = couponName + proInfoProDto.getName() + "+";
                            }
                        }
                        couponName = couponName.substring(0, couponName.length() - 1);
                        if (!couponName.equals("")) {
                            o.setCouponName(couponName);
                        }
                    }
                }
            }
        }
        return pageInfo;
    }

    /**
     * 查看订单详情
     *
     * @param orderId
     * @return
     */
    public OrderProductDto orderProductDetail(Long orderId) {
        OrderProductDto orderProductDto = orderProductServiceApi.findById(orderId);
        //附加信息
        if (null != orderProductDto) {
            //线下打款凭证信息
            List<OrderProductImageDto> list = orderProductImageServiceApi.findByOrderId(orderId);
            orderProductDto.setOrderProductImageList(list);
            //销售员信息
            SysUserAdminDto sysUserAdminDto = sysUserAdminServiceApi.selectByPrimaryKey(orderProductDto.getCreateUser());
            if (sysUserAdminDto != null) {
                orderProductDto.setUserName(sysUserAdminDto.getRealName());
                orderProductDto.setJobNumber(sysUserAdminDto.getJobNumber());
            } else {
                orderProductDto.setUserName("无");
                orderProductDto.setJobNumber("无");
            }
            DeptDto deptDto = deptServiceApi.findDeptDtoById(sysUserAdminDto.getDeptId());
            if (deptDto != null)
                orderProductDto.setDeptName(deptDto.getDeptName());
            else
                orderProductDto.setDeptName("浙江龙之游旅游开发有限公司");
            //产品信息
            ProductInfoDto productInfoDto = productInfoServiceApi.getProductProject(orderProductDto.getProductId());
            if (productInfoDto != null) {
                orderProductDto.setProductName(productInfoDto.getName());
                orderProductDto.setProductImage(productInfoDto.getCover());
                orderProductDto.setContractUrl(productInfoDto.getOffice());
                if (productInfoDto.getProjectList() != null && productInfoDto.getProjectList().size() > 0) {
                    String projectStr = "";
                    for (ProductInfoProjectDto pipd : productInfoDto.getProjectList()) {
                        if (pipd.getType() != null && pipd.getType().equals(0)) {
                            projectStr += (pipd.getName() + pipd.getContainNum() + pipd.getUnit() + "  +  ");
                        }
                    }
                    //产品单选项信息
                    ProjectDto projectDto = projectServiceApi.getById(orderProductDto.getProjectId());
                    if (projectDto != null) {
                        for (ProductInfoProjectDto pipd : productInfoDto.getProjectList()) {
                            if (projectDto.getId().equals(pipd.getProjectId())) {
                                projectStr += (pipd.getName() + pipd.getContainNum() + pipd.getUnit());
                            }
                        }
                        orderProductDto.setProjectVoDto(DozerUtils.map(projectDto, ProjectVoDto.class));
                        orderProductDto.setProjectStr(projectStr);
                    } else {
                        orderProductDto.setProjectStr(projectStr.substring(0, projectStr.length() - 5));
                    }
                }
                orderProductDto.setProjectList(productInfoDto.getProjectList());
            }
        }
        return orderProductDto;
    }

    /**
     * 查询会员列表
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    public PageInfo<OrderProductDto> selectMemberList(Pager pager, OrderProductDto orderProductDto) {
        PageInfo<OrderProductDto> pageInfo = orderProductServiceApi.selectMemberList(pager, orderProductDto);
        //客户信息
        if (null != pageInfo && null != pageInfo.getList() && pageInfo.getList().size() > 0) {
            for (OrderProductDto o : pageInfo.getList()) {
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                MemberUserDto memberUserDto = memberUserServiceApi.findById(o.getMemberId());
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
                if (memberUserDto != null)
                    o.setMemberName(memberUserDto.getNickName());
            }
        }
        return pageInfo;
    }

    /**
     * 查询会员合同列表
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    public PageInfo<OrderProductDto> selectMemberOrderList(Pager pager, OrderProductDto orderProductDto) {
        PageInfo<OrderProductDto> pageInfo = orderProductServiceApi.selectMemberOrderList(pager, orderProductDto);
        return pageInfo;
    }

    /**
     * 查询会员收益列表
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    public PageInfo<OrderProductDto> selectMemberIncomeList(Pager pager, OrderProductDto orderProductDto) {
        PageInfo<OrderProductDto> pageInfo = orderProductServiceApi.selectMemberOrderList(pager, orderProductDto);
        return pageInfo;
    }

    /**
     * 查询购买记录
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    public PageInfo<OrderProductDto> selectPurchaseList(Pager pager, OrderProductDto orderProductDto) {
        PageInfo<OrderProductDto> pageInfo = orderProductServiceApi.selectMemberOrderList(pager, orderProductDto);
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            List<OrderProductDto> orderProductDtoList = pageInfo.getList();
            for (OrderProductDto opDto : orderProductDtoList) {
                if (opDto != null && opDto.getProductId() != null) {
                    //获取卡券类型（如“房车券 + 代金券”）
                    ProductInfoProjectDto pipDto = new ProductInfoProjectDto();
                    pipDto.setProductId(opDto.getProductId());
                    List<ProductInfoProjectDto> pipList = productInfoProjectServiceApi.query(pipDto);
                    if (pipList != null && pipList.size() > 0) {
                        String couponName = "";
                        for (ProductInfoProjectDto proInfoProDto : pipList) {
                            if (proInfoProDto != null && proInfoProDto.getName() != null) {
                                couponName = couponName + proInfoProDto.getName() + "+";
                            }
                        }
                        couponName = couponName.substring(0, couponName.length() - 1);
                        if (!couponName.equals("")) {
                            opDto.setCouponName(couponName);
                        }
                    }
                }
            }
        }
        return pageInfo;
    }

    /**
     * 查询消费记录
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    public PageInfo<OrderProductDto> selectExpenseList(Pager pager, OrderProductDto orderProductDto) {


        return null;
    }

    /**
     * 查询账号信息
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    public PageInfo<OrderProductDto> selectAccountList(Pager pager, OrderProductDto orderProductDto) {
        PageInfo<OrderProductDto> pageInfo = orderProductServiceApi.selectList(pager, orderProductDto);
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            List<OrderProductDto> orderProductDtoList = pageInfo.getList();
            for (OrderProductDto opDto : orderProductDtoList) {
                if (opDto != null) {
                    if (opDto.getStatus() != null) {
                        opDto.setStatusName(BusinessType.CouponOrderType.getDesc(opDto.getStatus()));
                    }
                    //根据订单号获取收益比率
                    if (opDto.getOrderId() != null) {
                        OrderYieldRatioDto orderYieldRatioDto = orderYieldRatioServiceApi.findOrderYieldRatioByOrderId(opDto.getOrderId());
                        if (orderYieldRatioDto != null) {
                            opDto.setOrderYieldRatioDto(orderYieldRatioDto);
                        }
                        //订单产品包含项
                        List<OrderProjectRecordDto> orderProjectRecordDtoList = orderProjectRecordServiceApi.selectOrderProjectRecordByOrderId(opDto.getOrderId());
                        if (orderProjectRecordDtoList != null && orderProjectRecordDtoList.size() > 0) {
                            ProductInfoProjectDto[] productInfoProjectDtos = new ProductInfoProjectDto[orderProjectRecordDtoList.size()];
                            int i = 0;
                            for (OrderProjectRecordDto oprDto : orderProjectRecordDtoList) {
                                if (oprDto != null) {
                                    if (oprDto.getProjectId() != null) {
                                        ProductInfoProjectDto pipDto = new ProductInfoProjectDto();
                                        pipDto.setContainNum(oprDto.getCount());
                                        pipDto.setName(BusinessType.ProjectType.getDesc(oprDto.getProjectType()));
                                        productInfoProjectDtos[i] = pipDto;
                                        i++;
                                    }
                                }
                            }
                            opDto.setProductInfoProjectDtos(productInfoProjectDtos);
                        }
                    }
                }
            }
        }
        return pageInfo;
    }

    /**
     * 查看会员订单详情
     *
     * @param orderId
     * @return
     */
    public OrderProductDto memberOrderProductDetail(Long orderId) {
        OrderProductDto orderProductDto = orderProductServiceApi.findById(orderId);
        //附加信息
        if (null != orderProductDto) {
            //产品信息
            ProductInfoDto productInfoDto = productInfoServiceApi.getProductProject(orderProductDto.getProductId());
            if (productInfoDto != null) {
                orderProductDto.setProductName(productInfoDto.getName());
                orderProductDto.setProductImage(productInfoDto.getCover());
                orderProductDto.setContractUrl(productInfoDto.getOffice());
                orderProductDto.setContractName(productInfoDto.getOfficeName());
            }
        }
        return orderProductDto;
    }

    /**
     * 会员合同审核
     *
     * @param dto
     * @return
     */
    public Boolean verifyContract(OrderProductDto dto) {
        Boolean flag = Boolean.FALSE;
        if (dto.getContractVerify().equals(BusinessType.VerifyStatusEnum.YESVERIFY.getK())) {
            //1.将产品内容送至客户
            OrderProductDto orderDto = orderProductServiceApi.findById(dto.getOrderId());
            if (orderDto != null) {
                dto.setStatus(BusinessType.CouponOrderType.BACKING.getCode());//返现中状态
                flag = orderProductServiceApi.update(dto);
                //订单分利
                orderProductServiceApi.calculateProfit(orderDto);
                //获取订单关联包含项
                List<OrderProjectRecordDto> list = orderProjectRecordServiceApi.selectOrderProjectRecordByOrderId(dto.getOrderId());
                if (list != null) {
                    for (OrderProjectRecordDto recordDto : list) {
                        ProductInfoProjectDto productInfoProjectDto = new ProductInfoProjectDto();
                        productInfoProjectDto.setProductId(orderDto.getProductId());
                        productInfoProjectDto.setProjectId(recordDto.getProjectId());
                        productInfoProjectDto.setPrice(recordDto.getPrice());
                        List<ProductInfoProjectDto> projectList = productInfoProjectServiceApi.selectList(null ,productInfoProjectDto).getList();
                        if (projectList != null && projectList.size()>0) {
                            recordDto.setValidTime(projectList.get(0).getValidTime());
                        }

                    }
                }
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                paymentDistribution(list, orderDto);
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
                OrderYieldRatioDto yieldRatioDto = orderYieldRatioServiceApi.findOrderYieldRatioByOrderId(dto.getOrderId());
                if (yieldRatioDto != null ){
                    BigDecimal dailyIncome = couponProfitRecordServiceApi.calculateDayProfit(yieldRatioDto.getPrice(), yieldRatioDto.getCashbackTime());
                    yieldRatioDto.setStartDate(DateUtil.format(DateUtil.addDay(new Date(), 1), DateUtil.FORMAT_SHORT));
                    int days = CalendarUtil.daysBetween(yieldRatioDto.getCashbackTime());
                    //10元代理商每天分不到0.01，特殊处理为0.01（18-3-27）
                    if (orderDto.getMoneyCount() != null && orderDto.getMoneyCount().intValue()==10) {
                        yieldRatioDto.setDailyIncome(new BigDecimal(0.01));
                        //
                        if (days!=0 && days*0.01>10) {
                            days = 1000;
                        }
                    } else {
                        yieldRatioDto.setDailyIncome(dailyIncome);
                    }
                    yieldRatioDto.setEndDate(DateUtil.format(DateUtil.addDay(new Date(), (days + 1)), DateUtil.FORMAT_SHORT));
                    yieldRatioDto.setStatus(1);
                    orderYieldRatioServiceApi.updateOrderYieldRatio(yieldRatioDto);
                    MemberCouponsDto memberCouponsDto = new MemberCouponsDto();
                    memberCouponsDto.setMemberId(orderDto.getMemberId());
                    memberCouponsDto.setDragonMoney(yieldRatioDto.getPrice());
                    memberCouponsServiceApi.updateMemberCoupons(memberCouponsDto);
                }
            }
        } else {
            flag = orderProductServiceApi.update(dto);
        }
        return flag;
    }

    public void paymentDistribution(List<OrderProjectRecordDto> list, OrderProductDto orderDto) {
        if (list != null) {
            for (OrderProjectRecordDto project : list) {
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                MemberUserDto memberUserDto = memberUserServiceApi.findMemberByMobile(orderDto.getPhone());
                switch (project.getProjectId().intValue()) {
                    case 1://龙珠
                        LzLargessParamDTO lzParamDTO = new LzLargessParamDTO();
                        lzParamDTO.setMobile(orderDto.getPhone());
                        lzParamDTO.setUserId(orderDto.getMemberId());
                        lzParamDTO.setNumber(project.getCount());
                        lzParamDTO.setType(BusinessType.DragonStatus.product.getCode());
                        payMemberAccountApi.addLzSystemLargess(lzParamDTO);

                        PresentDto presentDto = new PresentDto();
                        presentDto.setGiveMemberId(1L);//表示系统赠送
                        presentDto.setAcceptMemberId(orderDto.getMemberId());
                        presentDto.setNumber(new BigDecimal(project.getCount()));
                        presentDto.setType(BusinessType.PresentType.DRAGON.getCode());
                        presentDto.setVerifyStatus(BusinessType.VerifyStatusEnum.YESVERIFY.getK());
                        presentServiceApi.addPresent(presentDto);
                        continue;
                    case 2://股权
                        if (memberUserDto != null) {
                            MemberAccountDto accountDto = memberAccountServiceApi.selectMemberAccountByCond(orderDto.getMemberId(), 3);
                            if (accountDto != null) {
                                MemberAccountDto memberAccountDto = new MemberAccountDto();
                                memberAccountDto.setType(3);//股权
                                memberAccountDto.setBalance(BigDecimalUtil.add(new BigDecimal(project.getCount()), accountDto.getBalance()));
                                memberAccountDto.setMemberId(memberUserDto.getId());
                                memberAccountDto.setId(accountDto.getId());
                                memberAccountServiceApi.updateMemberAccountInfo(memberAccountDto);
                            } else {
                                MemberAccountDto memberAccountDto = new MemberAccountDto();
                                memberAccountDto.setType(3);//股权
                                memberAccountDto.setBalance(new BigDecimal(project.getCount()));
                                memberAccountDto.setMemberId(memberUserDto.getId());
                                memberAccountServiceApi.addMemberAccount(memberAccountDto);
                            }
                        }
                        continue;
                    case 3://房车券
                        if (memberUserDto != null) {
                            CouponDto dto = checkCouponBatchAndTypeCode();
                            dto.setType(2);
                            dto.setRvType(BusinessType.CarCouponType.ALL_DAY_COUPON.getCode());
                            dto.setStartTime(DateUtil.fromNowStartTime());
                            dto.setValidTime(project.getValidTime());
                            dto.setNumber(project.getCount());
                            try {
                                List<Long> ids = couponServiceApi.addCoupon(dto);
                                MemberCouponDto memberCouponDto = new MemberCouponDto();
                                memberCouponDto.setMemberId(memberUserDto.getId());
                                dto.setMode(BusinessType.CouponMode.COLLAR_TIME.getCode());
                                memberCouponServiceApi.addMemberCoupon(dto, memberCouponDto);
                                addPresentLog(ids, 3, memberUserDto.getId());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                        continue;
                    case 4://套餐产品汽摩券
                        continue;
                    case 5://卡券宝房车券
                        if (memberUserDto != null) {
                            CouponDto dto = checkCouponBatchAndTypeCode();
                            dto.setType(2);
                            dto.setPrice(project.getPrice());
                            dto.setRvType(BusinessType.CarCouponType.AGENT_MONEY_COUPON.getCode());
                            dto.setStartTime(DateUtil.fromNowStartTime());
                            dto.setValidTime(project.getValidTime());
                            dto.setNumber(project.getCount());
                            try {
                                List<Long> ids = couponServiceApi.addCoupon(dto);
                                addMemberCoupon(ids, memberUserDto, dto, orderDto);
                                addPresentLog(ids, 3, memberUserDto.getId());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                        continue;
                    case 6://卡券宝汽摩券
                        if (memberUserDto != null) {
                            CouponDto dto = checkCouponBatchAndTypeCode();
                            dto.setType(2);
                            dto.setCategory(3);
                            dto.setPrice(project.getPrice());
                            dto.setRvType(BusinessType.CarCouponType.ALL_DAY_COUPON.getCode());
                            dto.setStartTime(DateUtil.fromNowStartTime());
                            dto.setValidTime(project.getValidTime());
                            dto.setNumber(project.getCount());
                            try {
                                List<Long> ids = couponServiceApi.addCoupon(dto);
                                addMemberCoupon(ids, memberUserDto, dto, orderDto);
                                addPresentLog(ids, 5, memberUserDto.getId());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                        continue;
                    default:
                        continue;
                }
            }
        }
    }

    /**
     * 添加赠送记录，用于收支详情
     *
     * @param ids
     * @param type
     * @param memberId
     */
    private void addPresentLog(List<Long> ids, Integer type, Long memberId) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        for (Long id : ids) {
            PresentDto present = new PresentDto();
            present.setNumber(new BigDecimal(1));
            present.setGiftId(id);
            present.setGiveMemberId(1L);
            present.setAcceptMemberId(memberId);
            present.setType(type);
            presentServiceApi.addPresent(present);
        }
        DataSourceHolder.clearDataSource();
    }

    public CouponDto checkCouponBatchAndTypeCode() {
        CouponDto dto = new CouponDto();
        dto.setBatch("9999");
        for (int i = 0; i < 9999; i++) {
            String typeCode = couponServiceApi.selectMaxTypeCode(dto.getBatch());
            if (typeCode != null) {
                if (Integer.valueOf(typeCode) < 9999) {
                    if (typeCode != null && !"".equals(typeCode)) {
                        dto.setTypeCode(StringUtil.leftPad(String.valueOf(Long.parseLong(typeCode) + 1), 4, "0"));
                    } else {
                        dto.setTypeCode("0001");
                    }
                    break;
                } else {
                    dto.setBatch(StringUtil.leftPad(String.valueOf(Long.parseLong(typeCode) - 1), 4, "0"));
                    typeCode = couponServiceApi.selectMaxTypeCode(dto.getBatch());
                    if (Integer.valueOf(typeCode) < 9999) {
                        if (typeCode != null && !"".equals(typeCode)) {
                            dto.setTypeCode(StringUtil.leftPad(String.valueOf(Long.parseLong(typeCode) + 1), 4, "0"));
                        } else {
                            dto.setTypeCode("0001");
                        }
                        break;
                    } else {
                        i++;
                    }
                }
            } else {
                dto.setTypeCode("0001");
                break;
            }
        }
        return dto;
    }


    public void addMemberCoupon(List<Long> ids, MemberUserDto memberUserDto, CouponDto dto, OrderProductDto orderDto) {
        for (Long id : ids) {
            MemberCouponDto memberCouponDto = new MemberCouponDto();
            memberCouponDto.setMemberId(memberUserDto.getId());
            memberCouponDto.setCouponId(id);
            memberCouponDto.setCouponStatus(1);
            memberCouponDto.setCouponPrice(dto.getPrice());
            memberCouponDto.setType(dto.getCategory());
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
            memberCouponServiceApi.insert(memberCouponDto);
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
            OrderCouponDto orderCouponDto = new OrderCouponDto();
            orderCouponDto.setCouponId(id);
            orderCouponDto.setOrderId(orderDto.getOrderId());
            orderCouponDto.setProductId(orderDto.getProductId());
            orderCouponServiceApi.createOrderCoupon(orderCouponDto);
            DataSourceHolder.clearDataSource();
        }
    }

    public OrderYieldRatioDto checkOrderYieldRatio(Long orderId){
        OrderYieldRatioDto orderYieldRatioDto = orderYieldRatioServiceApi.findOrderYieldRatioByOrderId(orderId);
        if(orderYieldRatioDto != null && orderYieldRatioDto.getMemberId() != null){
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
            MemberUserDto memberUserDto = memberUserServiceApi.selectMemberByMemberId(orderYieldRatioDto.getMemberId());
            if(memberUserDto != null && memberUserDto.getNickName() != null){
                orderYieldRatioDto.setNickName(memberUserDto.getNickName());
            }
            DataSourceHolder.clearDataSource();
        }
        return orderYieldRatioDto;
    }
}
